# coding=utf-8
from django.db.models import Q

from apps.organize_manager.models import *
from common.errorcode import *


def get_orgs_list():
    try:
        orgs = list(Orginazation.objects.filter(parent_id=None).values("id", "org_name", "org_code"))
        return orgs
    except Exception as e:
        print e
        return Errorquery(str(e))


def get_user_id(id):
    try:
        user = CloudAuthUser.objects.get(id=id)
        return user
    except Exception as e:
        return None


def get_user_auther(auther):
    try:
        user = CloudAuthUser.objects.get(author=auther)
        return user
    except Exception as e:
        return None


def get_all_org(params):
    try:
        orgs = Orginazation.objects.filter(**params).all()
        return orgs
    except Exception as e:
        print e
        return None


def get_all_orguser():
    try:
        orgs = get_all_org(params={"parent_id": None})
        org_list = []
        for org in orgs:
            org_object = {"text": org.org_name, "id": org.id}
            users = list(CloudAuthUser.objects.filter(Q(org=org) | Q(org__parent_id=org)).values("realname", "id"))
            for user in users:
                user["text"] = user["realname"]
            org_object["children"] = users
            org_list.append(org_object)
        
        return [{"children": org_list, "id": None, "text": "电信（陕西）云计算基地"}]
    except Exception as e:
        return None
